﻿using System;
using System.IO;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Resources;
using System.Text;

using CE.User;
using CE.Global;
using CE.Database;
using CE.InputOut;
using CE.CarInsurance;
using CE.Mail;

public partial class carinsurance_offline_CoverNoteList : System.Web.UI.Page
{

    protected override void InitializeCulture()
    {
        String selectedCulture = CE.Global.General.SetCulture();
        base.InitializeCulture();
    }

    private DateTime dateTimeNow = CE.Global.General.GetUTCDateTime();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session[CE.Global.General.UserId] == null)
        {
            Response.Redirect("~/SiteUserSecureLogin.aspx");
        }

        if (Session[General.UserRole] != null && Session[General.UserRole].ToString() == "201")
        {
            Response.Redirect("~/carinsurance/PendingApplication.aspx");
        }

        if (!IsPostBack)
        {
            divSendEmail.Visible = false;
        }
        else
        {
            lblError.Text = "";
            lblSendCoverNoteMessage.Text = "";
            lblNoError.Text = "";
        }
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        lblAgentEmail.Text = "";
        txtOnlineConfirmEmail.Text = "";
        txtCoverNoteNo.Text = "";
        txtVehicleCode.Text = "";
        lblCarPlate.Text = "";
        lblCustomerName.Text = "";
        lblAgentName.Text = "";
        lblAgentPhone.Text = "";
        lblCarID.Text = "";
        lblCarModel.Text = "";
        lblCustomerID.Text = "";
        txtSeat.Text = "";
        txtTypeofVehicle.Text = "";
        txtcc.Text = "";
        divSendEmail.Visible = false;
        txtAgentId.Text = Session[CE.Global.General.UserId].ToString();
        grvApplication.SelectedIndex = -1;
        LoadGrid();
    }

    protected void grvApplication_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (grvApplication.SelectedIndex >= 0 && Session[General.UserRole].ToString() != "100")
        {
            
            DataKey _dataKey = grvApplication.SelectedDataKey;
            string CarID = _dataKey[0].ToString();
            lblCarID.Text = CarID;
            string CustomerID = _dataKey[1].ToString();
            lblCustomerID.Text = CustomerID;
            lblCarPlate.Text = _dataKey[2].ToString();
            string QuoteRefNo = _dataKey[3].ToString();
            lblAgentEmail.Text = _dataKey[4].ToString();
            lblCustomerName.Text = grvApplication.Rows[grvApplication.SelectedIndex].Cells[2].Text; //Name
            Label lblSurName = (Label)grvApplication.Rows[grvApplication.SelectedIndex].FindControl("lblSurName");
            Label lblOfficeNumber = (Label)grvApplication.Rows[grvApplication.SelectedIndex].FindControl("lblOfficeNumber");
            Label lblCar = (Label)grvApplication.Rows[grvApplication.SelectedIndex].FindControl("lblCar");
            Label lblMedicalExpense = (Label)grvApplication.Rows[grvApplication.SelectedIndex].FindControl("lblMed");

            if (lblMedicalExpense.Text.Contains("("))
            {
                string[] openB = lblMedicalExpense.Text.Split('(');
                string[] closeB = openB[1].Split(')');
                txtSeat.Text = closeB[0];
            }

            lblAgentName.Text = grvApplication.Rows[grvApplication.SelectedIndex].Cells[8].Text + " " +
                lblSurName.Text; //FirstName + SurName
            lblAgentPhone.Text = lblOfficeNumber.Text; //OfficeNumber
            lblCarModel.Text = lblCar.Text;

            GetCustomerEmail(CarID, CustomerID);
        }
    }
    
    public void LoadGrid()
    {
        if (txtSearchLicensePlate.Text != "" || txtSearchReferenceNo.Text != "")
        {
            DataTable _dtSummary = new DataTable();
            string _SearchKey = "";
            if (txtSearchReferenceNo.Text != "")
                _SearchKey = Server.HtmlEncode(txtSearchReferenceNo.Text);
            else if (txtSearchLicensePlate.Text != "")
                _SearchKey = Server.HtmlEncode(txtSearchLicensePlate.Text);

            _SearchKey = _SearchKey.Replace("'", "");

            MyDatabase _db = new MyDatabase("GG_CRMDBConnectionString");
            string _spName = "[sprocCXCRMNonGGApplicationCompleteStatus]";
            SortedList _sPara = new SortedList();

            _sPara.Add("@SearchKey", _SearchKey);

            _dtSummary = _db.GetDataTableBySP(_spName, _sPara);
            if (_dtSummary != null && _dtSummary.Rows.Count > 0)
            {
                lblError.Text = "";
                grvApplication.DataSource = _dtSummary;
                grvApplication.DataBind();

                divSendEmail.Visible = true;

                if (_dtSummary.Rows.Count == 1)
                {
                    grvApplication.SelectedIndex = 0;
                    grvApplication_SelectedIndexChanged(null, null);
                }
            }
            else
            {
                grvApplication.DataSource = null;
                grvApplication.DataBind();
            }
        }
        else
        {
            grvApplication.DataSource = null;
            grvApplication.DataBind();
        }
    }

    private bool SendMailingStatusToCustomer()
    {
        bool _retValue = false;
        string CoverNoteNo = "";

        if (txtCoverNoteNo.Text != string.Empty)
        {
            CoverNoteNo = txtCoverNoteNo.Text;
        }

        DataSet _dsApplication = new DataSet();
        NonGGPackageDB _nonggpackagedb = new NonGGPackageDB();
        _dsApplication = _nonggpackagedb.GetCarDetails(Convert.ToInt64(lblCarID.Text.Trim()), Convert.ToInt64(lblCustomerID.Text.Trim()));
        CoverNotePDFOutput _nonGGPdf = new CoverNotePDFOutput();
        _nonGGPdf.AgentName = lblAgentName.Text;
        _nonGGPdf.AgentContactNo = lblAgentPhone.Text;
        _nonGGPdf.ResultGridSet = _dsApplication;
        _nonGGPdf.cc = txtcc.Text;
        _nonGGPdf.BodyType = txtTypeofVehicle.Text;
        _nonGGPdf.NumSeat = txtSeat.Text;
        _nonGGPdf.CoverNoteNo = txtCoverNoteNo.Text;
        _nonGGPdf.CarCode = txtVehicleCode.Text;
        string _fileName = _nonGGPdf.GeneratePDF();

        if (_fileName != "")
        {
            string _MSMailBody, _MSEmailTitle, _MSToEmail, _MSCCEmail, _MSBCCEmail;
            _MSMailBody = ""; _MSEmailTitle = ""; _MSToEmail = ""; _MSCCEmail = ""; _MSBCCEmail = "";

            string imgUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("CRMPath") + "/";

            StringBuilder strMailBody = new StringBuilder();
            strMailBody.Append(@"<html>
                            <head>
                            <meta charset='utf-8'>
                            <title>GluayGluay</title>
                            <style>
                            body {
	                            margin-left: 0px;
	                            margin-top: 0px;
	                            margin-right: 0px;
	                            margin-bottom: 0px;
	                            font-family: tahoma, Arial, sans-serif;
	                            font-size: 14px;
	                            color: #4F4356 ;
	                            background-repeat: repeat-x;
	                            background-color: #fff;
	                            text-decoration: none;
                            }
                            a:link  {text-decoration:none; color:#0674DB;}
                            hr{display: block; height: 1px;
                                border: 0; border-top: 1px solid #ccc;
                                margin: 1em 0; padding: 0;}
	                            .line-height{line-height:20px;}
	                            .table-txt{padding-left:5px;}
                            </style>
                            </head><body>
                            <div class='email-containter'>
                            <div class='email-banner'></div>
                            <div class='email-text'>
                            <table width='800' border='0' align='center' cellpadding='0' cellspacing='0'>
                            <tr>
                            <td height='653' align='right' valign='bottom' bgcolor='#FFFFFF'>
                            <table width='800' height='100' border='0' cellspacing='0' cellpadding='0'>");
            strMailBody.Append("<tr><td><span class='email-banner'><img src='" + imgUrl + "images/email-header.jpg' width='800' height='100' alt=''/></span></td>");
            strMailBody.Append(@"</tr>
                            </table>
                            <table width='800' border='0' align='center' cellpadding='0' cellspacing='0'>
                            <tr>
                                <td width='672' align='left' valign='top' bgcolor='#FFFFFF'>
                            <table border='0' cellspacing='0' cellpadding='0'>
                            <tr>
                            <td align='left'>");
            _MSMailBody = strMailBody.ToString();
            if (!chkExcelEng.Checked)
            {
                _MSEmailTitle = "ใบคำขอเอาประกันภัยรถยนต์ ทะเบียนรถ [" + lblCarPlate.Text + "]";
                _MSMailBody += "<p>เรียน  " + lblCustomerName.Text + ",<br/></p>";
                _MSMailBody += "ขอบคุณที่ใช้บริการของเว็บไซต์ <a href='http://www.gluaygluay.com'>กล้วยๆ.com</a><br/>";
                _MSMailBody += "บริษัทฯขอนำส่งเอกสารใบคำขอเอาประกันภัยรถยนต์ให้ท่าน (โปรดดูไฟล์แนบ)<br/>";
                _MSMailBody += "<p>ถ้ามีข้อสงสัยประการใด กรุณาติดต่อเรา อีเมลล์ ";
                _MSMailBody += "support@gluaygluay.com หรือ โทรหาเราที่เบอร์ <strong>02-2688222</strong></p>";

                _MSMailBody += "</td></tr><tr><td align=\"left\">";
                _MSMailBody += "ขอแสดงความนับถือ</td></tr></table><hr><p>" +
                                    "<br/><strong><a href='http://www.gluaygluay.com'>GluayGluay.com</a>ฝ่ายประสานงาน GluayGluay</strong><br/>" +
                                    "บริษัท คอมแพร์เอ็กซ์เพรส นายหน้าประกันภัย (ประเทศไทย) จำกัด<br/>" +
                                    "เลขทะเบียนนายหน้าประกันวินาศภัยนิติบุคคล เลขที่ ว00016/2553<br/>" +
                                    "42nd Floor, United Center Building,<br/>" +
                                    "323 Silom Road, Bangrak, Bangkok 10500</p>" +
                                    "<p>โทร. 02-268-8222 <br>โทรสาร 02-266-6339<br/>" +
                                    "<a href=\"mailto:support@gluaygluay.com\">support@gluaygluay.com</a></p></td>" +
                                    "</tr></table><hr>";
            }
            else
            {
                _MSEmailTitle = "Motor Insurance Cover Note for [" + lblCarPlate.Text + "]";
                _MSMailBody += "<p>Dear " + lblCustomerName.Text + ",<br/></p>";
                _MSMailBody += "Thank you for using <a href='http://www.gluaygluay.com'>GluayGluay.com</a><br/>";
                _MSMailBody += "Please find enclosed in PDF the proof of motor insurance cover note.";
                _MSMailBody += "<p>If your have any inquiry please contact us email : ";
                _MSMailBody += "support@gluaygluay.com or call us at <strong>02-2688222</strong></p>";

                _MSMailBody += "</td></tr><tr><td align=\"left\">";
                _MSMailBody += "With best regards,</td></tr></table><hr><p>" +
                "<br/><strong><a href='http://www.gluaygluay.com'>Gluaygluay.com</a>Support Team</strong><br/>" +
                "Comparexpress Insurance Broker ( Thailand ) Ltd,<br/>" +
                "License number  ว00016/2553<br/>" +
                "42nd Floor, United Center Building,<br/>" +
                "323 Silom Road, Bangrak, Bangkok 10500</p>" +
                "<p>Tel : 02-268-8222 , Fax : 02-266-6339<br/>" +
                "<a href=\"mailto:support@gluaygluay.com\">support@gluaygluay.com</a></p></td>" +
                "</tr></table><hr>";
            }

            string YearEn = dateTimeNow.Year.ToString();
            strMailBody = new StringBuilder();
            strMailBody.Append(@"<table width='300' border='0' align='center' cellpadding='0' cellspacing='0'><tr>");
            strMailBody.Append("<td width='44' style='text-align: center'><a href='https://www.facebook.com/GGmotor'><img src='" + imgUrl + "images/icons/fb-big.png' width='44' height='42' alt=''/></a></td>");
            strMailBody.Append("<td width='44' style='text-align: center'><a href='https://plus.google.com/+Gluaygluay/posts'><img src='" + imgUrl + "images/icons/g-plus-big.png' width='44' height='42' alt=''/></a></td>");
            strMailBody.Append("<td width='44' style='text-align: center'><a href='https://www.youtube.com/channel/UCZ4gMtlXymBHxvcXO2cR1vA'><img src='" + imgUrl + "images/icons/youtube-big.png' width='44' height='42' alt=''/></a></td>");
            strMailBody.Append("<td width='44' style='text-align: center'><a href='http://iconosquare.com/ggmotor'><img src='" + imgUrl + "images/icons/instagram-big.png' width='44' height='42' alt=''/></a></td>");
            strMailBody.Append("<td width='43' style='text-align: center'><a href='https://www.linkedin.com/company/-com-gluaygluay-com-'><img src='" + imgUrl + "images/icons/linkedin-big.png' width='44' height='42' alt=''/></a></td>");
            strMailBody.Append(@"</tr>
                                         </table>
                                         <table width='800' height='100' border='0' cellspacing='0' cellpadding='0' background='images/email-footer.jpg'>
                                            <tr>
                                              <td><p style='text-align: center'><br><br>
                                                © " + YearEn + " gluaygluay.com. All rights reserved.<br>");
            strMailBody.Append(Resources.EmailMessage.NoReply);
            strMailBody.Append(@"</p></td></tr>
                                          </table></td>
                                          </tr>
                                        </table>
                                        </body>
                                        </html>");
            _MSMailBody += strMailBody.ToString();

            _MSToEmail = txtOnlineConfirmEmail.Text;
            if (lblAgentEmail.Text.Trim() != "")
            {
                _MSCCEmail = lblAgentEmail.Text.Trim();
            }
            else
            {
                _MSCCEmail = CE.Configuration.MyConfigurationManager.GetAppSettingValue("SUPPORT");
            }
            _MSBCCEmail = "broker2@gluaygluay.com";

            string[] _file = new string[1];
            _file[0] = _fileName;
            _retValue = MyMailManager.SendGGMailWithAttach(ConfigurationManager.AppSettings["GGServiceSMTPAccount"].ToString(), ConfigurationManager.AppSettings["GGServiceSMTPAuthCode"].ToString(), _MSToEmail, _MSCCEmail, _MSBCCEmail, _MSEmailTitle, _MSMailBody, Session[General.SMTPReplyTo].ToString(), _file);

            return _retValue;
        }
        else
            return false;
    }

    private void GetCustomerEmail(string CarID, string CustomerID)
    {
        if (CarID != string.Empty && CustomerID != string.Empty)
        {
            MyDatabase _myDb = new MyDatabase();
            DataTable _dtLanguage = new DataTable("tblLanguage");
            _dtLanguage = _myDb.GetDataTable(@"SELECT Info2 FROM tblNonGGTransaction WHERE TransactionTypeId = 400 AND RefCEUserId = " + CustomerID + " AND CECarId = " + CarID);
            if (_dtLanguage != null && _dtLanguage.Rows.Count > 0)
            {
                if (_dtLanguage.Rows[0]["Info2"] != DBNull.Value && _dtLanguage.Rows[0]["Info2"].ToString() != string.Empty)
                {
                    txtOnlineConfirmEmail.Text = _dtLanguage.Rows[0]["Info2"].ToString();
                }
            }
        }
    }

    protected void btnSendCoverNote_Click(object sender, EventArgs e)
    {
        if (txtOnlineConfirmEmail.Text == "" || txtCoverNoteNo.Text == "" || txtcc.Text == "" ||
            txtSeat.Text == "" || txtTypeofVehicle.Text == "" || txtVehicleCode.Text == "")
            return;

        if (!SendMailingStatusToCustomer())
        {
            lblSendCoverNoteMessage.Text = "Error send email!";
        }
        else
        {
            lblNoError.Text = "Sent email successfully.";
        }
    }
}
